#include "stack.h"

//初始化
void STInit(ST* pst)
{
	assert(pst);
	pst->a = NULL;
	pst->capacity = 0;
	pst->top = 0;
}

//销毁
void STDestroy(ST* pst)
{
	assert(pst);
	free(pst->a);
	pst->top = 0;
	pst->capacity = 0;
}

//入栈
void STPush(ST* pst, STDataType x)
{
	assert(pst);
	//扩容
	if (pst->top == pst->capacity)//这里本质上是无多余空间的意思，不仅符合有空间被占满，还符合空间为0，元素也为0的情况
	{
		int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
		STDataType* tmp = (STDataType*)realloc(pst->a, newcapacity * sizeof(STDataType));//当pst->a==NULL时，还可以模拟malloc
		if (tmp == NULL)
		{
			perror("realloc");
			exit(1);
		}
		pst->a = tmp;
		pst->capacity = newcapacity;
	}
	pst->a[pst->top] = x;
	pst->top++;
}

//出栈
void STPop(ST* pst)
{
	assert(pst);
	assert(pst->top > 0);
	pst->top--;
}

//返回栈顶数据
STDataType STTop(ST* pst)
{
	assert(pst);
	assert(pst->top-1 > 0);
	return pst->a[pst->top-1];
}

//判空
bool STEmpty(ST* pst)
{
	assert(pst);
	assert(pst->top >= 0);
	if (pst->top == 0)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//栈内数据个数
int STSize(ST* pst)
{
	assert(pst);
	return pst->top;
}
